package yz.cp.back.auth.oauth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.error.DefaultOAuth2ExceptionRenderer;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import yz.cp.back.auth.oauth.exception.CustomWebResponseExceptionTranslator;
import yz.cp.back.auth.oauth.token.MyRedisTokenStore;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.sql.DataSource;

/**
 * @author xukk
 * @date 2018/3/14
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Resource
    private DataSource dataSource;
    @Autowired(required = false)
    private MyRedisTokenStore redisTokenStore;
    @Autowired(required = false)
    private JwtTokenStore jwtTokenStore;
    @Autowired(required = false)
    private JwtAccessTokenConverter jwtAccessTokenConverter;
    @Autowired
    @Qualifier("OauthUserDetailsService")
    private UserDetailsService userDetailsService;
    @Autowired
    private CustomWebResponseExceptionTranslator customWebResponseExceptionTranslator;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetails());
    }

    @Bean
    public ClientDetailsService clientDetails() {
        return new JdbcClientDetailsService(dataSource);
    }

    @Bean(name="daoAuthenticationProvider")
    public AuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
        return daoAuthenticationProvider;
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        if (jwtTokenStore != null) {
            endpoints.tokenStore(jwtTokenStore).authenticationManager(new AuthenticationManager() {
                @Override
                public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                    // TODO Auto-generated method stub
                    return daoAuthenticationProvider().authenticate(authentication);
                }

            });
        } else if (redisTokenStore != null) {
            endpoints.tokenStore(redisTokenStore).authenticationManager(new AuthenticationManager() {
                @Override
                public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                    // TODO Auto-generated method stub
                    return daoAuthenticationProvider().authenticate(authentication);
                }

            });
        }
        if (jwtAccessTokenConverter != null) {
            endpoints.accessTokenConverter(jwtAccessTokenConverter);
        }
        endpoints.userDetailsService(userDetailsService);
        endpoints.exceptionTranslator(customWebResponseExceptionTranslator);
    }


    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.tokenKeyAccess("permitAll()");
        security.checkTokenAccess("isAuthenticated()");
        OAuth2AccessDeniedHandler adh = new OAuth2AccessDeniedHandler();
        adh.setExceptionRenderer(new DefaultOAuth2ExceptionRenderer());
        adh.setExceptionTranslator(customWebResponseExceptionTranslator);
        security.accessDeniedHandler(adh);
        OAuth2AuthenticationEntryPoint oAuth2AuthenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
        oAuth2AuthenticationEntryPoint.setExceptionTranslator(customWebResponseExceptionTranslator);
        oAuth2AuthenticationEntryPoint.setRealmName("oauth2/client");
        oAuth2AuthenticationEntryPoint.setExceptionRenderer(new DefaultOAuth2ExceptionRenderer());
        security.authenticationEntryPoint(oAuth2AuthenticationEntryPoint);
        security.allowFormAuthenticationForClients();
        security.addObjectPostProcessor(new ObjectPostProcessor<Filter>() {
            @Override
            public <O extends Filter> O postProcess(O o) {
                if (o instanceof ClientCredentialsTokenEndpointFilter) {
                    ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter = (ClientCredentialsTokenEndpointFilter) o;
                    OAuth2AuthenticationEntryPoint oAuth2AuthenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
                    oAuth2AuthenticationEntryPoint.setExceptionTranslator(customWebResponseExceptionTranslator);
                    oAuth2AuthenticationEntryPoint.setRealmName("oauth2/client");
                    oAuth2AuthenticationEntryPoint.setTypeName("Form");
                    ((ClientCredentialsTokenEndpointFilter) o).setAuthenticationEntryPoint(oAuth2AuthenticationEntryPoint);
                }
                return o;
            }
        });
    }
}
